
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getConnection } from 'typeorm';
import { ICurrentUserType } from 'src/decorators/current.user';
import { PostsCommentInputDto } from '../resolvers/dto/post.comment.dto';
import { UserEntity } from '../../user/entities/user.entity';
import { CommentEntity } from '../entities/comment.entity';

@Injectable()
export class CommentService {
  constructor(
    @InjectRepository(CommentEntity)
    private readonly commentRepository: Repository<CommentEntity>,
  ) {}

  async postComment(
    userInfo: ICurrentUserType,
    postsCommentInputDto: PostsCommentInputDto,
  ): Promise<string> {
    console.log(userInfo, postsCommentInputDto);
    const result = this.commentRepository.create({
      ...postsCommentInputDto,
      userId: userInfo.userId,
    });
    await this.commentRepository.save(result);
    return '评论成功';
  }


  async commentList(
    commentInputDto: Omit<PostsCommentInputDto, 'comment'>,
  ): Promise<CommentEntity[]> {
    const { postId, parentId } = commentInputDto;
    const result = await getConnection()
      .createQueryBuilder(CommentEntity, 'comment')
      .select('comment.id', 'id')
      .addSelect('comment.userId', 'userId')
      .addSelect('comment.postId', 'postId')
      .addSelect('comment.comment', 'comment')
      .addSelect('comment.parentId', 'parentId')
      .addSelect('comment.createdAt', 'createdAt')
      .addSelect('comment.updatedAt', 'updatedAt')
      .addSelect(
        (qb) =>
          qb
            .select('username', 'username')
            .from(UserEntity, 'user')
            .where('user.id = comment.userId'),
        'username',
      )
      .where('(comment.postId =:postId and comment.parentId =:parentId)', { postId, parentId })
      .getRawMany();
    return result;
  }
}
